package com.googlecode.jasmincc.framework.namespace.implementation;

import static com.googlecode.ptrace.Ptrace.*;

import com.googlecode.jasmincc.framework.namespace.Namespace;
import com.googlecode.jasmincc.framework.namespace.NamespaceManager;
import com.googlecode.jasmincc.framework.services.*;
import java.io.*;
import java.util.*;

public class SimpleNamespaceManager implements NamespaceManager {
	List<Namespace> namespaces = null;

	FilenameFilter filenameFilter = null;

	GetGrammarNameByFile getGrammarNameByFile = null;

	protected SimpleNamespaceFactory namespaceFactory = null;

	public void setNamespaceFactory(SimpleNamespaceFactory namespaceFactory) {
		this.namespaceFactory = namespaceFactory;
	}

	public void setFilenameFilter(FilenameFilter filenameFilter) {
		this.filenameFilter = filenameFilter;
	}

	public void setGetGrammarNameByFile(GetGrammarNameByFile getGrammarNameByFile) {
		this.getGrammarNameByFile = getGrammarNameByFile;
	}

	public SimpleNamespaceManager() {
		namespaces = new ArrayList<Namespace>();
	}

	public void addNamespace(String name) {
		try {
			Namespace namespace = namespaceFactory.getNamespace(name);
			namespaces.add(namespace);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void addNamespace(Namespace namespace) {
		namespaces.add(namespace);
	}

	public boolean isAnInterface(String name) {
		// TODO change it with a more specific implementation
		return name.startsWith("!");
	}

	public File getEntity(String name) throws NullPointerException {
		File file = null;
		int dot = name.lastIndexOf('.');
		ptrace(name);
		String namespaceName = name.substring(0, dot);
		ptrace(namespaceName);
		String entityName = name.substring(dot + 1);
		ptrace(entityName);

		for (Namespace namespace : namespaces) {
			if (namespace.getName().equals(namespaceName)) {
				file = namespace.getEntity(entityName);
				if (file != null) {
					return file;
				}
			}
		}

		return null;
	}

	public Namespace getNamespace(String name) {
		for (Namespace namespace : namespaces) {
			if (namespace.getName().equals(name)) {
				ptrace(namespace.getName());
				return namespace;
			}
		}

		return null;
	}

}
